//
//  WebViewController.m
//  cookBook
//
//  Created by xalo on 16/1/22.
//  Copyright © 2016年 张广斌. All rights reserved.
//

#import "WebViewController.h"
#import "Model.h"
#import "RecordHelper.h"
#import "CollectionHelper.h"
@interface WebViewController ()

@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *string = [NSString stringWithFormat:@"http://ibaby.ipadown.com/api/food/food.show.detail.php?id=%@",self.model.ID];
    
    self.title = self.model.title;
    
    //webView请求数据
    NSURL *url = [NSURL URLWithString:string];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    self.webView.scalesPageToFit = YES;
    
    [self.webView loadRequest:request];
    
    
    //添加到记录
    [self insertToRecord];
    
    
    //添加收藏按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"收藏" style:(UIBarButtonItemStylePlain) target:self action:@selector(collectionAction)];

    
    // Do any additional setup after loading the view.
}



//添加到浏览记录
- (void)insertToRecord
{
    
    Model *model = [[RecordHelper sharedManager] selectWithID:self.model.ID];
  
    //判断记录数据库中是否存在
    if (![self.model.ID isEqualToString:model.ID]) {
        NSLog(@"添加到数据库");
        //添加到浏览记录数据库
        
        [[RecordHelper sharedManager] insertToSqlitWithModel:self.model ID:self.model.ID];
    }
}



//收藏
- (void)collectionAction
{
    Model *model = [[CollectionHelper sharedManager] selectWithID:self.model.ID];
    
    if (![self.model.ID isEqualToString:model.ID]) {
        
        //添加到收藏
        BOOL result = [[CollectionHelper sharedManager] insertToSqlitWithModel:self.model ID:self.model.ID];
        
        if (result) {
            
            [self addAlertView:@"收藏成功"];
            
        }
        
    }
    else
    {
        [self addAlertView:@"已收藏过"];
    }
    
}



// 提示框
- (void)addAlertView:(NSString *)info
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:info delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    
    [alert show];
    
    [alert dismissWithClickedButtonIndex:0 animated:YES];

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
